package cn.chenyumeng.blog.controller.admin;

import cn.chenyumeng.blog.dto.CommonResponse;
import cn.chenyumeng.blog.dto.ResultCode;
import cn.chenyumeng.blog.dto.TagDTO;
import cn.chenyumeng.blog.service.admin.TagService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.List;

/**
 * @program: blog->TagController
 * @description:
 * @author: cg
 * @create: 2020-07-27 16:52
 **/
@Validated
@RestController
@ResponseBody
@RequestMapping("/admin/tag")
public class TagController {

    @Autowired
    private TagService tagService;

    @GetMapping("/queryAllTag")
    public CommonResponse queryAllTag() {
        List<TagDTO> list = tagService.queryAll();
        if (list ==null) {
            return null;
        }
        return CommonResponse.ok(list);
    }

    @GetMapping("/queryAllByLimit")
    public CommonResponse queryAllByLimit(@RequestParam(name = "page", defaultValue = "1") Integer page,
                                          @RequestParam(name = "size", defaultValue = "10") Integer size) {
        PageInfo<TagDTO> pageInfo = tagService.queryAllByLimit(page, size);
        if (pageInfo == null) {
            return CommonResponse.build(ResultCode.SYS_ERROR);
        }
        return CommonResponse.ok(pageInfo);
    }

    @GetMapping("/getTagByName")
    public CommonResponse getTagByName(@NotBlank(message = "标签名称不能为空") String name) {
        TagDTO tagDTO = tagService.getTagByName(name);
        if (tagDTO == null) {
            return CommonResponse.ok();
        }
        return CommonResponse.ok(tagDTO);
    }

    @PostMapping("/saveTag")
    public CommonResponse saveType(@Validated TagDTO tagDTO) {
        TagDTO insert = tagService.insert(tagDTO);
        if (insert == null) {
            return CommonResponse.build(ResultCode.PARAM_IS_EXIST);
        }
        return CommonResponse.ok(insert.getId());
    }

    @PostMapping("/updateTag")
    public CommonResponse updateType(@Validated TagDTO tagDTO) {
        if (tagDTO.getId() == null) {
            return CommonResponse.build(ResultCode.PARAM_TYPE_BIND_ERROR);
        }
        TagDTO update = tagService.update(tagDTO);
        if (update == null) {
            return CommonResponse.build(ResultCode.PARAM_IS_EXIST);
        }
        return CommonResponse.ok(update.getId());
    }

    @GetMapping("/deleteTagById")
    public CommonResponse deleteTypeById(@RequestParam(name = "id") Long id) {
        if (tagService.deleteById(id)) {
            return CommonResponse.ok();
        } else {
            return CommonResponse.build(ResultCode.PARAM_IS_INVALID);
        }
    }

}
